<template>
    <el-dialog v-model="visible" title="配置详情" width="78%" :close-on-click-modal="false">
        <div class="detail-wrapper" v-if="detailData">
            <!-- 基础信息 -->
            <div class="detail-content">
                <div class="detail-item">
                    <span class="detail-label">域名：</span>
                    <span class="detail-value">{{ detailData.domain || "" }}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">隐私协议：</span>
                    <span class="detail-value">{{ detailData.privacyPolicy || "" }}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">用户手册：</span>
                    <span class="detail-value">{{ detailData.userManual || "" }}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Imprint：</span>
                    <span class="detail-value">{{ detailData.Imprint || "" }}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">联系方式：</span>
                    <span class="detail-value">{{ detailData.contact || "" }}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">UI模板：</span>
                    <span class="detail-value">{{ detailData.uiTemplate || "" }}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">网站标签：</span>
                    <el-tag v-for="item in detailData.tagList" effect="plain" type="primary" :key="item" round>
                        {{ item }}
                    </el-tag>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Category：</span>
                    <el-tag v-for="item in detailData.category" effect="plain" type="primary" :key="item" round>
                        {{ item }}
                    </el-tag>
                </div>
            </div>

            <!-- 文章列表 -->
            <div class="article-list-section">
                <h3 class="section-title">文章列表</h3>
                <div class="table-container">
                    <el-table :data="tableData" v-loading="loading"
                        :header-cell-style="{ background: '#fafafa', height: '56px' }" :max-height="tableMaxHeight">
                        <template v-for="(item, index) in tableHeader" :key="index">
                            <el-table-column :prop="item.prop" :label="item.label" :min-width="item.width"
                                :fixed="index === 0">
                                <template #default="scope">
                                    <span style="cursor: pointer" v-if="item.prop === 'id'"
                                        @click="handlegoDetail(scope.row)">
                                        {{ scope.row[item.prop] }}
                                    </span>
                                    <div v-else-if="item.prop === 'image' && scope.row[item.prop]"
                                        style="width: 120px; height: 100%;">
                                        <el-image style="width: 100%; height: 100%" :src="scope.row[item.prop]"
                                            :zoom-rate="1.2" preview-teleported
                                            :preview-src-list="[scope.row[item.prop]]" :max-scale="7" :min-scale="0.2"
                                            fit="cover" />
                                    </div>
                                    <span v-else-if="item.prop === 'status'">{{ StatusMap[scope.row[item.prop]]
                                    }}</span>
                                    <span v-else-if="item.prop === 'accountId'">
                                        {{scope.row?.['accountId'] === -1 ? '其他' : accountNameOptions?.filter((item) =>
                                            item.id == scope.row?.['accountId'])[0]?.name}}
                                    </span>
                                    <span v-else-if="item.prop === 'langId'">
                                        {{languageOptions?.filter((item) => item.id ==
                                            scope.row?.['langId'])[0]?.langName || scope.row?.['langId']}}
                                    </span>
                                    <span v-else-if="item.prop === 'siteId'">
                                        <a target="_blank" v-if="scope.row?.['siteId'] !== 4"
                                            style="text-decoration: none;color: #1677ff;"
                                            :href="'https://' + scope.row?.['siteUrl']">
                                            {{ scope.row?.['siteUrl'] }}
                                        </a>
                                        <div v-else style="display: flex;flex-direction: column;">
                                            <span v-for="(item, index) in allSiteOptions?.filter((item) => item.id !==
                                                scope.row?.['siteId'])">
                                                <a target="_blank" style="text-decoration: none;color: #1677ff;" :href="'https://' + item?.siteUrl
                                                    ">
                                                    {{ item?.siteName }}
                                                </a>
                                            </span>
                                        </div>
                                    </span>
                                    <span v-else>{{ scope.row[item.prop] }}</span>
                                </template>
                            </el-table-column>
                        </template>
                        <el-table-column label="操作" width="190" fixed="right">
                            <template #default="scope">
                                <div style="display: flex;align-items: center;gap: 15px;flex-wrap: wrap;">
                                    <span style="display: flex;align-items: center;">
                                        <el-dropdown placement="bottom-start" trigger="click">
                                            <el-icon style="cursor: pointer;color: #1677ff;">
                                                <Postcard />
                                            </el-icon>
                                            <template #dropdown>
                                                <el-dropdown-menu>
                                                    <template v-for="(item, index) in tagIdList" :key="index">
                                                        <el-dropdown-item @click="() => {
                                                            handleUpdateTag(item.id, scope.row)
                                                        }">
                                                            <el-icon style="color: green;"
                                                                v-if="scope.row.tagList?.map((item) => item.id)?.includes(item.id)">
                                                                <CircleCheck />
                                                            </el-icon>
                                                            <div v-else style="width: 18px;"></div>
                                                            {{ item.tagNameEn }}
                                                        </el-dropdown-item>
                                                    </template>
                                                </el-dropdown-menu>
                                            </template>
                                        </el-dropdown>
                                    </span>
                                    <span style="cursor: pointer;color: #1677ff;"
                                        @click="handleCheck('check', scope.row.id)">查看</span>
                                    <span style="cursor: pointer;color: #1677ff;"
                                        @click="handleCheck('edit', scope.row.id)">编辑</span>
                                    <span style="cursor: pointer;color: red;"
                                        @click="handleDelete(scope.row.id)">删除</span>
                                    <span style="cursor: pointer;color: #1677ff;"
                                        @click="handleAddCampaign(scope.row.id)">新建Campaign</span>
                                    <span style="cursor: pointer;color: #1677ff;"
                                        @click="handleCheckFlow(scope.row.id)">查看跑量</span>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="pagination-container">
                    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize"
                        style="display: flex;justify-content: end;" layout="total,prev, pager, next,sizes"
                        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">关闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Postcard, CircleCheck } from '@element-plus/icons-vue'
import service from '../../config'
import router from '../../router'

interface DetailData {
    id?: string
    domain?: string
    privacyPolicy?: string
    userManual?: string
    Imprint?: string
    contact?: string
    uiTemplate?: string
    tagList?: string[]
    category?: any[]
    createdAt?: string | Date
    updatedAt?: string | Date
}

interface Props {
    modelValue: boolean
    detailData?: DetailData | null
}

const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    detailData: null
})

const emit = defineEmits<{
    'update:modelValue': [value: boolean]
}>()

const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
})

// 格式化标签
const formatTags = (tags?: string[]) => {
    if (!tags || tags.length === 0) return ""
    return tags.join(', ')
}

// 格式化分类
const formatCategory = (category?: any[]) => {
    if (!category || category.length === 0) return ""
    if (Array.isArray(category)) {
        return category.join(', ')
    }
    return String(category)
}

// 格式化日期
const formatDate = (date?: string | Date) => {
    if (!date) return ""
    const d = new Date(date)
    if (isNaN(d.getTime())) return ""

    return d.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    })
}

// 文章列表相关
const loading = ref(false)
const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tagIdList = ref([])
const accountNameOptions = ref([])
const allSiteOptions = ref([])
const languageOptions = ref([])

// 计算表格最大高度
const tableMaxHeight = computed(() => {
    return window.innerHeight * 0.65 - 310
})

enum StatusMap {
    通过 = 1,
    驳回,
    审核中,
    已归档,
    新版本审核中,
    新版本驳回
}

const tableHeader = ref([
    { label: '文章ID', prop: 'id', width: 200 },
    { label: '标题', prop: 'title', width: 200 },
    { label: '封面图', prop: 'image', width: 200 },
    { label: '生成者', prop: 'creator', width: 150 },
    { label: '状态', prop: 'status', width: 100 },
    { label: '分类', prop: 'articleCategory', width: 200 },
    { label: '语言', prop: 'langId', width: 120 },
    { label: '账户名称', prop: 'accountId', width: 120 },
    { label: '所属网站', prop: 'siteId', width: 200 },
    { label: '上线时间', prop: 'publishDate', width: 200 },
    { label: '修改时间', prop: 'modified', width: 200 }
])

// 加载文章列表
const loadArticleList = () => {
    loading.value = true
    service.post('/article/page', {
        pageNum: pageNum.value,
        pageSize: pageSize.value
    })
        .then(response => {
            tableData.value = response.data?.records || []
            total.value = response?.data?.total || 0
        })
        .catch(error => {
            ElMessage.error(error?.message || '加载文章列表失败')
        })
        .finally(() => {
            loading.value = false
        })
}

// 获取标签列表
const getTagAll = () => {
    service.get('/tag/getAll')
        .then(response => {
            tagIdList.value = response.data
        })
        .catch(error => {
            ElMessage.error(error?.message)
        })
}

// 获取账户列表
const getAccount = () => {
    service.get('/account/getAll')
        .then(response => {
            accountNameOptions.value = response?.data || []
            accountNameOptions.value.push({ id: -1, name: '其他' })
        })
        .catch(error => {
            ElMessage.error(error?.message)
        })
}

// 获取网站列表
const getSite = () => {
    service.get('/site/getAll')
        .then(response => {
            allSiteOptions.value = response?.data || []
        })
        .catch(error => {
            ElMessage.error(error?.message)
        })
}

// 获取语言列表
const getLanguages = () => {
    service.get('/lang/getAll')
        .then(response => {
            languageOptions.value = response?.data || []
        })
        .catch(error => {
            ElMessage.error(error?.message)
        })
}

// 分页处理
const handleSizeChange = () => {
    pageNum.value = 1
    loadArticleList()
}

const handleCurrentChange = () => {
    loadArticleList()
}

// 更新标签
const handleUpdateTag = (tagId: number, row: any) => {
    service.post('/article/updateTag', {
        op: row?.tagList?.map((item: any) => item.id)?.includes(tagId) ? 0 : 1,
        articleId: row?.id,
        tagId: tagId
    })
        .then(response => {
            loadArticleList()
        })
        .catch(error => {
            ElMessage.error(error?.message)
        })
}

// 查看/编辑文章（这里需要根据实际情况实现）
const handleCheck = (type: string, id: string) => {
    // TODO: 根据实际需求实现
    ElMessage.info('此功能需要在父组件中实现')
}

// 删除文章
const handleDelete = (id: string) => {
    service.post('/article/delete', { id })
        .then(response => {
            ElMessage.success('删除成功！')
            loadArticleList()
        })
        .catch(error => {
            ElMessage.error(error?.message)
        })
}

// 新建Campaign
const handleAddCampaign = (id: string) => {
    router.push({
        name: 'Campaign',
        query: { articleId: id }
    })
}

// 查看跑量
const handleCheckFlow = (id: string) => {
    router.push({
        name: 'Flow',
        query: { articleId: id }
    })
}

// 跳转到文章详情
const handlegoDetail = (row: any) => {
    window.open(`${'https://' + row?.['siteUrl']}/detail/${row.id}`, '_blank')
}

// 监听弹窗打开，加载数据
watch(() => props.modelValue, (newVal) => {
    if (newVal && props.detailData) {
        pageNum.value = 1
        getTagAll()
        getAccount()
        getSite()
        getLanguages()
        loadArticleList()
    }
})

// 关闭对话框
const handleClose = () => {
    visible.value = false
    // 重置数据
    tableData.value = []
    pageNum.value = 1
    total.value = 0
}
</script>

<style lang="scss" scoped>
.detail-wrapper {
    max-height: 68vh;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
}

.detail-content {
    padding: 15px 20px;
    background: #f8f9fa;
    border-radius: 8px;
    margin-bottom: 6px;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;

    .detail-item {
        margin-bottom: 12px;
        display: flex;
        align-items: flex-start;

        .detail-label {
            font-weight: 600;
            color: #2c3e50;
            width: 100px;
            flex-shrink: 0;
            font-size: 14px;
        }

        .detail-value {
            color: #606266;
            flex: 1;
            font-size: 14px;
            word-break: break-word;
        }
    }
}

.article-list-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;

    .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #2c3e50;
        padding-bottom: 10px;
        margin-bottom: 10px;
        border-bottom: 2px solid #1677ff;
        flex-shrink: 0;
    }

    .table-container {
        flex: 1;
        min-height: 0;
    }

    .pagination-container {
        flex-shrink: 0;
        padding-top: 15px;
    }
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

:deep(.el-table__row) {
    font-size: 13px;
}
</style>
